package com.hooper.controller;

import com.hooper.anno.TokenIgnore;
import com.hooper.common.JwtHelper;
import com.hooper.common.Result;
import com.hooper.emun.ResultCodeEnum;
import com.hooper.exception.BusinessException;
import com.hooper.model.vo.LoginVo;
import com.hooper.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Tim Hooper
 * @version 1.0
 * @time 2023/03/29/14:43
 */
@Api(tags = "后台登录管理")
@RequestMapping("admin/system/backend")
@RestController
@Slf4j
public class BackendLoginController {
    @Resource
    private SysUserService userService;

    @ApiOperation("登录")
    @TokenIgnore
    @PostMapping("login")
    public Result login(@RequestBody LoginVo loginVo) {
        log.info("loginVo:{}", loginVo);
        if (loginVo == null) {
            throw new BusinessException(ResultCodeEnum.NULL_PARAM);
        }
        String token = userService.login(loginVo);
        Map<String, String> map = new HashMap<>(1);
        map.put("token", token);
        return Result.ok(map);
    }

    //info
    @ApiOperation("获取用户信息")
    @GetMapping("info")
    public Result info(HttpServletRequest request) {

        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            throw new BusinessException(ResultCodeEnum.TOKEN_EXPIRED);
        }
        Long userId = JwtHelper.getUserId(token);
        Map<String, Object> map =  userService.getUserInfo(userId);

//        map.put("roles", new String[]{"admin"});
        map.put("introduction", "xxx");
        map.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        map.put("name",JwtHelper.getUsername(token));
//        map.put("routers", null);
//        map.put("buttons", null);
        log.info("userInfo:{}", map);
        return Result.ok(map);
    }

    //logout
    @ApiOperation("退出登录")
    @PostMapping("logout")
    public Result logout() {
        return Result.ok();
    }
}
